package com.vis.xxljob;

import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.*;

import java.net.URI;
import java.nio.file.Paths;

public class RustfsS3Example {

    public static void main(String[] args) {
        var i = 0;
        S3Client s3 = S3Client.builder()
                .endpointOverride(URI.create("http://39.103.63.7:9000")) // RustFS 地址
                .region(Region.US_EAST_1) // 可写死，RustFS 不校验 region
                .credentialsProvider(
                        StaticCredentialsProvider.create(
//                                AwsBasicCredentials.create("XbfEwQ7VZO2cHmeClxqW", "hFo0bcPN1yqpRUnjBeYOCs3kMulfDrVH6zQaX58t")
                                AwsBasicCredentials.create("rustfsadmin", "rustfsadmin")
                        )
                )
                .forcePathStyle(true) // 关键配置！RustFS 需启用 Path-Style
                .build();
        while (i++ < 200) {

//        {"accessKey":"lpFT7COi0nPUEDKkIMgV","secretKey":"A0Voe29vzRf7jLuIlHsQnkdm1P4TyKMxEa3iJbXB","api":"s3v4","path":"auto"}
            // 1. 初始化 S3 客户端

            // 2. 创建 Bucket
            String bucket = "my-bucket";
            try {
                s3.createBucket(CreateBucketRequest.builder().bucket(bucket).build());
                System.out.println("Bucket created: " + bucket);
            } catch (BucketAlreadyExistsException | BucketAlreadyOwnedByYouException e) {
                System.out.println("Bucket already exists.");
            }

            // 3. 上传文件
            s3.putObject(
                    PutObjectRequest.builder().bucket(bucket).key("hello.txt").build(),
                    Paths.get("hello.txt")
            );
            System.out.println("Uploaded hello.txt");

            // 4. 下载文件
            s3.getObject(
                    GetObjectRequest.builder().bucket(bucket).key("hello.txt").build(),
                    Paths.get("down/"+System.currentTimeMillis() + "downloaded-hello.txt")
            );
            System.out.println("Downloaded hello.txt");

            // 5. 列出对象
            ListObjectsV2Response listResponse = s3.listObjectsV2(ListObjectsV2Request.builder().bucket(bucket).build());
            listResponse.contents().forEach(obj -> System.out.println("Found object: " + obj.key()));

            // 6. 删除对象
            s3.deleteObject(DeleteObjectRequest.builder().bucket(bucket).key("hello.txt").build());
            System.out.println("Deleted hello.txt");

            // 7. 删除桶（可选）
            // s3.deleteBucket(DeleteBucketRequest.builder().bucket(bucket).build());
        }

    }
}